﻿using RXY_Mall.Domain;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Security.Cryptography;
using System.Text;
using System.Threading.Tasks;
using System.Web;

namespace RXY_Mall.Core.Tool
{
    public class RxyHttpUtils
    {
        private static string RXY_SECRET = "0257701b6ef8d1f8c9e7f7d9fcd95c49";//accessToken
        //private const string HOST_URL = "rxy.invosoft.cn";
        //private static string PREFIX_URL = "http://rxy.invosoft.cn/rxymall/";//url前缀
        private const string HOST_URL = "rxy.rxysoft.cn";
        private static string PREFIX_URL = "http://rxy.rxysoft.cn/rxymall/";//url前缀
        private const string SERVER_KEY = "serverNameCookie";//服务器ID
        private const string ENTERPRISE_KEY = "enterpriseNameCookie";//企业ID
        public static Cookie cookie = new Cookie();
        public static CookieContainer cookieContainer;

        /// <summary>
        /// 服务器启动时初始化通讯的IP和Port、访问凭证
        /// </summary>
        /// <param name="ipAndPort">IP和Port</param>
        /// <param name="accessToken">访问凭证</param>
        public static void initIPAndToken(string ipAndPort, string accessToken)
        {
            PREFIX_URL = "http://" + ipAndPort + "/xsm/";
            RXY_SECRET = accessToken;
        }

        /// </summary>
        /// 通过Http Post进行请求，并获取响应结果
        /// </summary>
        /// <param name="sync_url">请求Url</param>
        /// <param name="parameter">需要传输的参数</param>
        /// <remarks> Create By Scenery 2012-12-11</remarks>
        public static string TransferSync_Post(string serverID, string enterpriseID, string sync_url, string parameter)
        {
            try
            {
                System.Net.ServicePointManager.Expect100Continue = false;
                // 开始请求
                System.Net.HttpWebRequest request = (System.Net.HttpWebRequest)WebRequest.Create(PREFIX_URL + sync_url);

                // 请求方式
                request.Method = "POST";
                // 内容类型
                request.ContentType = "application/x-www-form-urlencoded";


                request.KeepAlive = false;

                request.ProtocolVersion = HttpVersion.Version10;

                //设置cookie++++++++++++++++++++++++++++++++++++++++++++++++++++++++
                #region 写入Cookies
                request.CookieContainer = new CookieContainer();
                Cookie cookie = new Cookie(SERVER_KEY, serverID);
                cookie.Path = "/";
                cookie.Domain = HOST_URL;
                request.CookieContainer.Add(cookie);
                Cookie cookie2 = new Cookie(ENTERPRISE_KEY, enterpriseID);
                cookie2.Path = "/";
                cookie2.Domain = HOST_URL;
                request.CookieContainer.Add(cookie2);
                #endregion

                //设置传递的参数++++++++++++++++++++++++++++++++++++++++++++++++++++                
                StringBuilder sbParameter = new StringBuilder();
                sbParameter.Append("requestData");
                sbParameter.Append("=");
                sbParameter.Append(parameter);
                sbParameter.Append("&signatureResult");
                sbParameter.Append("=");
                var md5 = CommonHelper.GetMD5(parameter + RXY_SECRET);
                String signatureStr = GetMd5Hash(parameter + RXY_SECRET);
                //md5 = "65c171e750d727c6e0ec7d0610b34549";
                sbParameter.Append(md5);
                // 将字符串转化为字节
                byte[] transfer_arr = Encoding.UTF8.GetBytes(sbParameter.ToString());

                // 设置请求内容长度
                request.ContentLength = transfer_arr.Length;

                //获得请求流
                using (Stream writer = request.GetRequestStream())
                {
                    // 将请求参数写入流
                    writer.Write(transfer_arr, 0, transfer_arr.Length);
                }
                string response_value;

                // 获取响应流
                using (System.Net.HttpWebResponse response = (System.Net.HttpWebResponse)request.GetResponse())
                {
                    using (System.IO.StreamReader sr = new StreamReader(response.GetResponseStream()))
                    {
                        response_value = sr.ReadToEnd();
                    }
                }
                return response_value;
            }
            catch (Exception ex)
            {
                LogHelper.WriteLog(ex, "TransferSync_Post");
                return "{\"msg\":\"" + ex.Message + "\",\"code\":\"0\"}";
            }
        }

        /// <summary>
        /// 将指定的字符串进行MD5加密码
        /// </summary>
        /// <param name="input">需要加密的字符串</param>
        /// <remarks>Create By Scenery 2012-12-11</remarks>
        /// <returns>加密后的字符串</returns>
        public static string GetMd5Hash(string input)
        {
            // Create a new instance of the MD5CryptoServiceProvider object.
            MD5 md5Hasher = MD5.Create();

            // Convert the input string to a byte array and compute the hash.
            byte[] data = md5Hasher.ComputeHash(Encoding.UTF8.GetBytes(input));

            // Create a new Stringbuilder to collect the bytes
            // and create a string.
            StringBuilder sBuilder = new StringBuilder();

            // Loop through each byte of the hashed data 
            // and format each one as a hexadecimal string.
            for (int i = 0; i < data.Length; i++)
            {
                sBuilder.Append(data[i].ToString("x2"));
            }

            // Return the hexadecimal string.
            return sBuilder.ToString();
        }



    }
}
